<?php
namespace  App\Libraries;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
class Weixin {
    //获取微信用户信息
    //$r_urlcode  回调url
    //$type 获取类型   默认获取用户信息
    public static function get_user($r_urlcode,$type="snsapi_userinfo") {
        $r_url = env("APP_URL")."/".$r_urlcode;
        $r_url = urlencode($r_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".env('WX_APPID')."&redirect_uri=".$r_url."&response_type=code&scope=".$type."&state=STATE#wechat_redirect";
        $str = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".env('WX_APPID')."&secret=".env('WX_SECRET')."&code=".@$_GET['code']."&grant_type=authorization_code");
        $str = json_decode($str,true);
        if(is_null(@$str['access_token'])){
            header("Location: ".$url);die;
        }
        $userinfo = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".@$str['access_token']."&openid=".@$str['openid']."&lang=zh_CN");
        $userinfo = json_decode($userinfo,true);
        return $userinfo;

    }
    //获取微信access_token
    public static function get_access_token(){
        if (Cache::has('wx_access_token'))
        {
            //Cache::forget('wx_access_token');

            return Cache::get('wx_access_token');
        }else{
            $data = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".env('WX_APPID')."&secret=".env('WX_SECRET'));
            $data = json_decode($data,true);
            $expiresAt = Carbon::now()->addMinutes(100);
            Cache::put('wx_access_token',@$data['access_token'], $expiresAt);
            return Cache::get('wx_access_token');
        }

    }
}
?>